package com.sixbing.demo.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import com.hjq.toast.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.yanzhenjie.permission.Request;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


/**
 * Created by xiangl
 * on 2018/4/26 0026 上午 10:30
 * description :
 */
public abstract class BaseActivity<T extends BasePresenterI, V> extends AppCompatActivity implements BaseViewI<V> {
    /**
     * 子类标识
     */
    protected String TAG;
    protected T mPresenter;
    public Context mContext;
    public Activity mActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
        setContentView(getLayoutId());
        mContext = this;
        mActivity = this;
        initView();
    }

    /**
     * 加载载布局
     */
    public abstract int getLayoutId();

    /**
     * 初始化view
     */
    protected abstract void initView();


    public void launch(Class clazz) {
        startActivity(new Intent(this, clazz));
    }

    public void launch(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void showDataError(String errorMessage) {
        showToast(errorMessage);
    }


    @Override
    public void showDataSuccess(V datas) {
    }

    /**
     * 获取Presenter
     */
    public T getPresenter() {
        try {
            Object obj = this.getMyClass().newInstance();
            return (T) obj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unSubcrible();
        }
    }

    /**
     * 左入右出的动画
     */
    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
//        overridePendingTransition(R.anim.slide_right_in, 0);
    }

    @Override
    public void finish() {
        super.finish();
//        overridePendingTransition(R.anim.slide_right_out,0);
    }

    //得到泛型类T
    Class getMyClass() {
        System.out.println(this.getClass());
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] ptype = ((ParameterizedType) type).getActualTypeArguments();
            return (Class) ptype[0];  //将第一个泛型T对应的类返回（这里只有一个）
        } else {
            return Object.class;//若没有给定泛型，则返回Object类
        }

    }


    public void showToast(String s) {
        ToastUtils.show(s);
    }

    /************************************************** 6.0以上系统判断权限  --> start ***************************************/


    public static final int REQUEST_CODE_PERMISSION_MULTI = 101;
    public static final int REQUEST_CODE_SETTING = 300;

    /**
     * 获取权限
     */
    public void getPerMission(String... permissions) {
        Request request = AndPermission.with(this);
        if (permissions != null && permissions.length > 0) {
            request.permission(permissions);
        } else {
            request.permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WAKE_LOCK);
        }
        request.requestCode(REQUEST_CODE_PERMISSION_MULTI)
                .callback(this)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(mContext, rationale).show();
                    }
                }).start();
    }

    public void permissionRefuse() {
        showToast("您拒绝了相关权限，可能无法使用此功能！");
    }

    public void permissionAgree() {
    }

    /**
     * 检测GPS是否打开
     *
     * @return
     */
    public boolean checkGPSIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }

}
